package com.qiguliuxing.dts.core.notify;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.qiguliuxing.dts.core.config.WxProperties;
import com.qiguliuxing.dts.db.domain.DtsOrder;
import com.qiguliuxing.dts.db.domain.DtsUserFormid;
import com.qiguliuxing.dts.db.service.DtsUserFormIdService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信公众号模版消息通知
 */
public class WxMpTemplateSender {
	private final Log logger = LogFactory.getLog(WxMpTemplateSender.class);
	@Autowired
	private WxMpService wxMpService;


	public void wxMpNoticeMsg(String openId,  String[] parms,NotifyType notifyType, String templateId) {
		List<WxMpTemplateData> data = new ArrayList<>();
		switch (notifyType.getType()){
			//下单
			case "placeOrder":
				//订单编号
				data.add(new WxMpTemplateData("character_string6", parms[0]));
				//商品名称
				data.add(new WxMpTemplateData("thing7", parms[1]));
				//客户名称
				data.add(new WxMpTemplateData("thing16", parms[2]));
				//订单金额
				data.add(new WxMpTemplateData("amount3" ,parms[3]));
				//下单时间
				data.add(new WxMpTemplateData("time9" ,parms[4]));
				buildSend(openId, data,templateId);
				break;
			//退款申请
			case "applyRefund":
				//订单编号
				data.add(new WxMpTemplateData("character_string4", parms[0]));
				//退款商品
				data.add(new WxMpTemplateData("thing2", parms[1]));
				//退款金额
				data.add(new WxMpTemplateData("amount3", parms[2]));
				//申请时间
				data.add(new WxMpTemplateData("time5" ,parms[3]));
				buildSend(openId, data,templateId);
				break;
			default:
				break;
		}
	}

	private void buildSend(String openId, List<WxMpTemplateData> data, String templateId) {
		WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
				.toUser(openId)
				//.url("www.baidu.com")
				.templateId(templateId)
				.build();
		templateMessage.setData(data);
		try {
			wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			logger.info("订阅消息发送成功");
		} catch (WxErrorException e) {
			logger.error("订阅消息发送失败:" + e.getError().getErrorMsg());
		}
	}
}
